package com.cj.dubbo.protocool.http;

import com.cj.dubbo.DispatchServlet;
import org.apache.catalina.*;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;

/**
 * @author chan
 * @dateTime 2022/9/28  13:48:50
 * 本地服务启动
 */
public class HttpServer {

    public void start(String hostName, Integer port) {
        // 创建tomcat服务器
        Tomcat tomcatServer = new Tomcat();

        Server server = tomcatServer.getServer();
        Service service = server.findService("Tomcat");
        // 指定端口号
        Connector connector = new Connector();
        connector.setPort(port);

        Engine engine = new StandardEngine();
        engine.setDefaultHost(hostName);

        Host host = new StandardHost();
        host.setName(hostName);

        String contextPath = "";
        Context context = new StandardContext();
        context.setPath(contextPath);
        context.addLifecycleListener(new Tomcat.FixContextListener());

        host.addChild(context);
        engine.addChild(host);

        service.setContainer(engine);
        service.addConnector(connector);

        tomcatServer.addServlet(contextPath, "dispatcher", new DispatchServlet());
        context.addServletMappingDecoded("/*","dispatcher");
        try {
            tomcatServer.start();
            tomcatServer.getServer().await();
        } catch (LifecycleException e) {
            throw new RuntimeException(e);
        }
        System.out.println("tomcat start success..");
        // 异步进行接收请求
    }
}
